// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.assets.service.impl;

import com.liuxinlong.common.AosException;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.assets.dto.OutSupplierDto;
import com.liuxinlong.modules.assets.service.AssetsSupplierService;
import com.liuxinlong.modules.dao.AssetsSupplierDao;
import com.liuxinlong.modules.entity.AssetsSupplier;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.out.service.OutOrderService;
import com.liuxinlong.modules.out.service.OutSupplierService;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 供应商信息业务接口层实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2023-10-31
 */
@Service
@Slf4j
public class AssetsSupplierServiceImpl implements AssetsSupplierService {

    @Autowired
    private AssetsSupplierDao assetsSupplierDao;

    @Autowired
    private OutOrderService outOrderService;

    @Autowired
    private OutSupplierService outSupplierService;

    @Override
    @Transactional
    public List<Map<String, Object>> pageAssetsSupplierInfo(Map<String, Object> queryParam) {
        int startNum = (int) queryParam.get("startNum");
        List<AssetsSupplier> originalList = assetsSupplierDao.pageAssetsSupplierInfo(queryParam);
        List<Map<String, Object>> resultList = completeResult(originalList, startNum);
        return resultList;
    }

    @Override
    public int getAssetsSupplierInfoCount(Map<String, Object> queryParam) {
        return assetsSupplierDao.getAssetsSupplierInfoCount(queryParam);
    }

    @Override
    @Transactional
    public void addAssetsSupplierInfo(AssetsSupplier assetsSupplier) {
        String id = SnowFlake.nextIdStr();
        assetsSupplier.setId(id);
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        assetsSupplier.setCreateUser(currentUser.getId());
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        assetsSupplier.setCreateTime(currentTime);
        assetsSupplierDao.insert(assetsSupplier);
    }

    @Override
    @Transactional
    public void updateAssetsSupplierInfo(AssetsSupplier assetsSupplierInfo) {
        String id = assetsSupplierInfo.getId();
        if (StringUtils.isEmpty(id)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改供应商信息失败，供应商信息不存在！");
        }
        AssetsSupplier oldInfo = assetsSupplierDao.selectById(id);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改供应商信息失败，供应商信息不存在！");
        }
    }

    @Override
    @Transactional
    public void deleteAssetsSupplierInfo(String id) {
        AssetsSupplier assetsSupplier = assetsSupplierDao.selectById(id);
        if (ObjectUtils.isEmpty(assetsSupplier)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除失败，供应商信息不存在！");
        }
        assetsSupplierDao.deleteById(id);
    }

    @Override
    public void syncSupplierInfo() {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        List<OutSupplierDto> outSupplierDtoList = outSupplierService.querySupplierList();
        Map<String,Map<String,String>> supplierMap = assetsSupplierDao.getAssetsSupplierMap();
        List<AssetsSupplier> addList = new ArrayList<>();
        List<AssetsSupplier> updateList = new ArrayList<>();
        List<String> deleteList = new ArrayList<>();
        Map<String,Map<String,String>>  supplierDbMap = new HashMap<>(supplierMap);
        for (OutSupplierDto outDto : outSupplierDtoList) {
            String supplierCode = outDto.getSupplierCode().toUpperCase();
            String domain = outDto.getDomain().toUpperCase();
            String outKey = supplierCode + "-" + domain;
            if (supplierMap.containsKey(outKey)) {
                supplierDbMap.remove(outKey);
                Map<String,String> supplierInfo = supplierMap.get(outKey);
                if (StringUtils.equals(supplierInfo.get("supplierName"),outDto.getSupplierName())) {
                    continue;
                }
                AssetsSupplier updateInfo = new AssetsSupplier();
                updateInfo.setId(supplierInfo.get("id"));
                updateInfo.setSupplierName(outDto.getSupplierName());
                updateInfo.setSupplierCode(supplierCode);
                updateInfo.setDomain(domain);
                updateInfo.setRemark(outDto.getRemark());
                updateInfo.setCreateUser(supplierInfo.get("create_user"));
                updateInfo.setCreateTime(supplierInfo.get("create_time"));
                updateInfo.setUpdateTime(currentTime);
                updateInfo.setUpdateUser(currentUser.getId());
                updateList.add(updateInfo);
                continue;
            }
            AssetsSupplier addInfo = new AssetsSupplier();
            addInfo.setId(SnowFlake.nextIdStr());
            addInfo.setSupplierName(outDto.getSupplierName());
            addInfo.setSupplierCode(supplierCode);
            addInfo.setDomain(domain);
            addInfo.setRemark(outDto.getRemark());
            addInfo.setCreateUser(currentUser.getId());
            addInfo.setCreateTime(currentTime);
            addList.add(addInfo);
        }
        if (!updateList.isEmpty()) {
            assetsSupplierDao.updateBatchById(updateList);
        }
        if (!addList.isEmpty()) {
            assetsSupplierDao.insertBatch(addList);
        }
        if (supplierDbMap.isEmpty()) {
            return;
        }
        for (Map<String,String> item :supplierMap.values()) {
            deleteList.add(item.get("id"));
        }
        if (!deleteList.isEmpty()) {
            assetsSupplierDao.deleteBatchIds(deleteList);
        }
    }

    /**
     * 补全数据
     *
     * @param originalList 原始数据
     * @param startNum     数据起始值
     * @return 补全数据列表
     */
    private List<Map<String, Object>> completeResult(List<AssetsSupplier> originalList, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        int sort = startNum + 1;
        for (AssetsSupplier assetsInfo : originalList) {
            Map<String, Object> item = ObjectUtils.object2Map(assetsInfo);
            item.put("sort", sort);
            resultList.add(item);
            sort++;
        }
        return resultList;
    }
}
